global repayoption  xti("Years") ///
	xlabel(365 "1" 730 "2" 1095 "3" 1460 "4", grid) leg(off)

	
*--- Open and prepare the data
use "${datadir}\HTB_main", replace

// keep only those that match with Land Reg (first sale)
drop _merge
merge 1:1 psd_id using "${datadir}\landreg_psd_matched_first_sale_new", keep(3) nogen

// add in repeat sales
merge 1:1 psd_id using "${datadir}\landreg_matched_htb_main_resold"
// from 04_LandReg_repeatsales_newhomes

bysort psd_id (dated): gen duration = dated_next - date

replace duration = . if duration < 0 


// Limit coverage up to Sept 17 to be consistent with Figure in the paper
gen yearmonth_next = ym(year(dated_next), month(dated_next))
replace duration = . if yearmonth_next >= ym(2017, 9)


*--- Simple analysis by cohort

forvalues year = 2013 / 2016 {
	preserve
		keep if year == `year'
		keep if htb_dummy == 1
		
		count // for r(N) later
		
		sort duration
		keep duration
		gen cumrepay`year'_el = _n /  r(N)
		
		collapse (max) cumrepay`year'_el, by(duration)
		
		tempfile cumrepay`year'_el
		save `cumrepay`year'_el'
	restore
	
	preserve
		keep if year == `year'
		keep if htb_dummy == 0
		
		count
		
		sort duration
		keep duration
		gen outcome`year'_noel = _n  /  r(N)
		
		collapse (max) outcome`year'_noel, by(duration)
		
		tempfile outcome`year'_noel
		save `outcome`year'_noel'	
	restore

	preserve
		use `cumrepay`year'_el', clear
		merge 1:1 duration using `outcome`year'_noel', gen(merge`year'_noel)
		line cumrepay`year'_el outcome`year'_noel ///
			duration if !mi(duration), sort ///
			${graphoption} ${repayoption} ///
			ti("`year' cohort") name(gr`year', replace) ///
			lpattern(solid dash) leg(on) leg(label(1 "EL") label(2 "no EL"))
	restore
}

gr combine gr2013 gr2014 gr2015 gr2016, graphregion(color(white))	///
	ycommon
graph export "${figuredir}\cumulative_rsales_psd_0917_ycommon.pdf", as(pdf) replace
